package com.shop.Exception;

import com.shop.common.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 
 * 统一处理系统异常，返回标准格式的错误响应
 * 
 * @author Shop Management System
 * @version 1.0
 * @since 2024-01-01
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理重复数据异常
     */
    @ExceptionHandler(DuplicateDataException.class)
    public Result<String> handleDuplicateDataException(DuplicateDataException e) {
        return Result.error(400, e.getMessage());
    }

    /**
     * 处理数据库约束违反异常
     */
    @ExceptionHandler(java.sql.SQLIntegrityConstraintViolationException.class)
    public Result<String> handleSQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException e) {
        String message = e.getMessage();
        if (message.contains("Duplicate entry")) {
            if (message.contains("phone")) {
                return Result.error(400, "手机号已存在，请使用其他手机号");
            } else if (message.contains("card_number")) {
                return Result.error(400, "会员卡号已存在，请使用其他卡号");
            } else if (message.contains("product_code")) {
                return Result.error(400, "商品编码已存在，请使用其他编码");
            } else {
                return Result.error(400, "数据已存在，请检查输入信息");
            }
        }
        return Result.error(500, "数据库操作失败：" + e.getMessage());
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<String> handleRuntimeException(RuntimeException e) {
        return Result.error(500, "系统错误：" + e.getMessage());
    }

    /**
     * 处理通用异常
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        return Result.error(500, "系统异常：" + e.getMessage());
    }
} 